<?php
	require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'class.api.php');

	class API_QUESTION extends API
	{

		var $fields = array (
			'questionid',
			'title',
			'answer',
			'lastupdated',
			'views',
			'related',
			'visible',
			'sortorder',
			'userid',
			'posvotes',
			'negvotes',
			'score',
			'emailed',
			'detectrelated',
			'metakeywords',
			'metadescription',
			'startdate',
			'enableexpiry',
			'expirydate',
			'featured',
			'workflowstatus'
		);

		var $pk = 'questionid';

		var $versioned = true;

		var $questionid = 0;
		var $title = '';
		var $answer = '';
		var $lastupdated='';
		var $views=0;
		var $related='';
		var $visible=0;
		var $sortorder=0;
		var $userid=0;
		var $posvotes=0;
		var $negvotes=0;
		var $score=0;
		var $emailed=0;
		var $detectrelated=0;
		var $metakeywords = '';
		var $metadescription = '';
		var $startdate;
		var $enableexpiry;
		var $expirydate;
		var $featured = 0;
		var $workflowstatus = WF_STATUS_AUTO_APPROVED;

		/**
		* Constructor
		* Initialize class specific values
		*
		* @return void
		*/
		function API_QUESTION()
		{
			parent::API();
			$this->attachmentDir = realpath(dirname(__FILE__).'/../../attachments');
		}

		/**
		* save
		* save the question back to the database
		*
		* @return bool was the save successful ?
		*/
		function save()
		{
			if (!isset($_POST['lastupdated']) || empty($_POST['lastupdated']) ) {
				$_POST['lastupdated'] = date('Y-m-d H:i:s', strtotime('now'));
			}
			
			$saveResult = parent::save();
			
			if ($saveResult) {
				if (isset($GLOBALS['enableFullindexPopulation']) && $GLOBALS['enableFullindexPopulation'] == true) {
					$GLOBALS['AKB_DB']->UpdateFullTextIndex(array($GLOBALS["tablePrefix"].'questions'), array($GLOBALS["tablePrefix"].'Q_FI_T', $GLOBALS["tablePrefix"].'Q_FI_A', $GLOBALS["tablePrefix"].'Q_FI_M'));
					$GLOBALS['AKB_DB']->UpdateFullTextIndex(array($GLOBALS["tablePrefix"].'questions_history'), array($GLOBALS["tablePrefix"].'QH_FI_T', $GLOBALS["tablePrefix"].'QH_FI_A', $GLOBALS["tablePrefix"].'QH_FI_M'));
				}
			}
			return $saveResult;
		}

		/**
		* create
		* create a new question in the database
		*
		* @return bool was the creation successful ?
		*/
		function create()
		{
			if (!isset($_POST['lastupdated']) || empty($_POST['lastupdated']) ) {
				$_POST['lastupdated'] = date('Y-m-d H:i:s', strtotime('now'));
			}
			
			if (!isset($_POST['related']) || empty($_POST['related']) ) {
				$_POST['related'] = '0';
			}
			
			if (!isset($_POST['startdate']) || empty($_POST['startdate']) ) {
				$_POST['startdate'] = date('Y-m-d H:i:s', strtotime('now'));
			}
			
			if (!isset($_POST['enableexpiry']) || empty($_POST['enableexpiry']) ) {
				$_POST['enableexpiry'] = '0';
			}
			
			if (!isset($_POST['expirydate']) || empty($_POST['expirydate']) ) {
				$_POST['expirydate'] = date('Y-m-d H:i:s', strtotime('now'));
			}
			
			$new_question_id = parent::create();
			
			if ($new_question_id) {
				if (isset($GLOBALS['enableFullindexPopulation']) && $GLOBALS['enableFullindexPopulation'] == true) {
					$GLOBALS['AKB_DB']->UpdateFullTextIndex(array($GLOBALS["tablePrefix"].'questions'), array($GLOBALS["tablePrefix"].'Q_FI_T', $GLOBALS["tablePrefix"].'Q_FI_A', $GLOBALS["tablePrefix"].'Q_FI_M'));
					$GLOBALS['AKB_DB']->UpdateFullTextIndex(array($GLOBALS["tablePrefix"].'questions_history'), array($GLOBALS["tablePrefix"].'QH_FI_T', $GLOBALS["tablePrefix"].'QH_FI_A', $GLOBALS["tablePrefix"].'QH_FI_M'));
				}
			}
			return $new_question_id;
		}
		
		/**
		* set_category_associations
		* sets the category associations for this category.
		*
		* @return bool was the category mapping successful?
		*/		
		function set_category_associations($new_question_id) {
			if ((isset($_POST['category_ids'])) && (is_array($_POST['category_ids'])) && (count($_POST['category_ids']) > 0)) {
				foreach ($_POST['category_ids'] as $catid) {
					if ($catid > 0) {
						$query = sprintf("insert into %scategoryassociations(categoryid, questionid) values(%d, %d)", $GLOBALS["tablePrefix"], $catid, (int)$new_question_id);
						$GLOBALS['AKB_DB']->Query($query);
						if (isset($_POST['workflowstatus']) && ($_POST['workflowstatus'] == WF_STATUS_APPROVED || $_POST['workflowstatus'] == WF_STATUS_AUTO_APPROVED)) {
							$query = sprintf("insert into %scatassoc_history(categoryid, questionid) values(%d, %d)", $GLOBALS["tablePrefix"], $catid, (int)$new_question_id);
							$GLOBALS['AKB_DB']->Query($query);
						}
					}
				}
			}
			
			return true;
		}
		
		/**
		* get_category_associations
		* gets the category associations for this category.
		*
		* @return bool was the category mapping successful?
		*/		
		function get_category_associations($question_id) {
			$categories = array();
			$query = sprintf("select categoryid from %scategoryassociations where questionid = '%d'", $GLOBALS["tablePrefix"], (int)$question_id);
			$GLOBALS['AKB_DB']->Query($query);
			$result = $this->db->Query($query);
	
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$categories[] = $row['categoryid'];
			}
			return $categories;
		}
		
		/**
		* get_owner
		* gets the owner for this question.
		*
		* @return bool was the category mapping successful?
		*/		
		function get_owner($question_id) {
			$userid = 0;
			$query = sprintf("select userid from %squestions where questionid = '%d'", $GLOBALS["tablePrefix"], (int)$question_id);
			$GLOBALS['AKB_DB']->Query($query);
			$result = $this->db->Query($query);
	
			while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$userid = $row['userid'];
			}
			return $userid;
		}
		
		/**
		* delete_category_associations
		* sets the category associations for this category.
		*
		* @return bool was the delete successful?
		*/		
		function delete_category_associations($question_id) {
			// Delete the associations in the categoryassociations table
			$query = "DELETE FROM `".$this->tablePrefix."categoryassociations`
			WHERE `questionid` IN (".((int) $question_id).")";
			$this->db->Query($query);
			
			$query = "DELETE FROM `".$this->tablePrefix."catassoc_history`
			WHERE `questionid` IN (".((int) $question_id).")";
			$this->db->Query($query);
			
			return true;
		}

		/**
		* delete
		* delete the question from the db
		*
		* @param int $id the id of the question to delete
		*
		* @return bool was the deletion successful ?
		*/
		function delete($id=0)
		{
			// Delete the entry from the questions table
			if (!parent::delete($id)) {
				return false;
			}

			// Delete the assocaitions in the categoryassociations table
			$this->delete_category_associations($id);

			// Delete any subscribers to the question
			$query = "DELETE FROM `".$this->tablePrefix."subscribers`
			WHERE `questionid` IN (".((int) $id).")";
			$this->db->Query($query);

			// Delete any history for the question
			$query = "DELETE FROM `".$this->tablePrefix."questions_history`
			WHERE `questionid` IN (".((int) $id).")";
			$this->db->Query($query);

			// Delete any comments for the question
			$query = "DELETE FROM `".$this->tablePrefix."comments`
			WHERE `questionid` IN (".((int) $id).")";
			$this->db->Query($query);

			// Delete any ratings for the question
			$query = "DELETE FROM `".$this->tablePrefix."ratings`
			WHERE `questionid IN` (".((int) $id).")";
			$this->db->Query($query);

			// Delete the attachments
			$this->deleteAttachments($id);

			return true;
		}

		/**
		* multiDelete
		* Delete multiple questions in one go
		*
		* @param array $ids The ids to delete
		*
		* @return bool was the deletion successful ?
		*/
		function multiDelete($ids=0)
		{
			// Delete the question itself
			if (!parent::multiDelete($ids)) {
				return false;
			}

			// Delete the assocaitions in the categoryassociations table
			$query = "DELETE FROM `".$this->tablePrefix."categoryassociations`
			WHERE `questionid` IN (".(implode(',', array_keys($ids))).")";
			$this->db->Query($query);

			// Delete the assocaitions in the catassoc_history table
			$query = "DELETE FROM `".$this->tablePrefix."catassoc_history`
			WHERE `questionid` IN (".(implode(',', array_keys($ids))).")";
			$this->db->Query($query);

			// Delete any subscribers to the question
			$query = "DELETE FROM `".$this->tablePrefix."subscribers`
			WHERE `questionid` IN (".(implode(',', array_keys($ids))).")";
			$this->db->Query($query);

			// Delete any history for the question
			$query = "DELETE FROM `".$this->tablePrefix."questions_history`
			WHERE `questionid` IN (".(implode(',', array_keys($ids))).")";
			$this->db->Query($query);

			// Delete any comments for the question
			$query = "DELETE FROM `".$this->tablePrefix."comments`
			WHERE `questionid` IN (".(implode(',', array_keys($ids))).")";
			$this->db->Query($query);

			// Delete any ratings for the question
			$query = "DELETE FROM `".$this->tablePrefix."ratings`
			WHERE `questionid` IN (".(implode(',', array_keys($ids))).")";
			$this->db->Query($query);

			// Delete any custom fields data for the question
			$query = "DELETE FROM `".$this->tablePrefix."questions_customfields 
			WHERE `questionid` IN (".(implode(',', array_keys($ids))).")";
			$this->db->Query($query);

			// Delete any pageindex for the question
			$query = "DELETE FROM `".$this->tablePrefix."pageindex 
			WHERE `questionid` IN (".(implode(',', array_keys($ids))).")";
			$this->db->Query($query);

			// Delete any attachments for the question
			foreach (array_keys($ids) as $id) {
				$this->deleteAttachments($id);
			}

			return true;
		}


		/**
		* deleteAttachments
		*
		* Delete all the attachments and the attachments directory for
		* a given question id
		*
		* @param integer $id The id to delete the attachments from
		*
		* @return void
		*/
		function deleteAttachments($id)
		{
			$php_errormsg = '';

			if (!$this->is_positive_int($id)) {
				$this->error = GetLang('apiIdNotAPosInt');
				return false;
			}

			if (empty($this->attachmentDir)) {
				$this->error = sprintf(GetLang('apiDirNotExists'), $this->attachmentDir);
				return false;
			}

			$dir = $this->attachmentDir.DIRECTORY_SEPARATOR.$id;
			if (is_dir($dir)) {
				if ($dh = opendir($dir)) {
					while (($file = readdir($dh)) !== false) {
						if ($file != '.' && $file != '..') {
							if (is_file($dir.DIRECTORY_SEPARATOR.$file)) {
								if (!unlink($dir.DIRECTORY_SEPARATOR.$file)) {
									$this->error = sprintf(GetLang('apiUnlinkFailed'), $php_errormsg);
								}
							} else {
								$this->error = sprintf(GetLang('apiNotAFile'), $dir.DIRECTORY_SEPARATOR.$file);
							}
						}
					}
					closedir($dh);
					rmdir($dir);
				} else {
					$this->error = sprintf(GetLang('apiDirOpenFailed'), $dir);
				}
			} else {
				$this->error = sprintf(GetLang('apiDirNotExists'), $dir);
			}
		}

		/**
		* valdiate_questionid
		*
		* Ensure the questionid is a pos int
		*
		* @param string $var
		*
		* @return bool
		*/
		function validate_questionid($var)
		{
			return $this->is_positive_int($var);
		}

		/**
		* validate_userid
		*
		* Ensure the userid is a pos int
		*
		* @param string $var
		*
		* @return bool
		*/
		function validate_userid($var)
		{
			return $this->is_positive_int($var);
		}

		/**
		* validate_title
		*
		* Ensure the title isn't empty and isn't too long
		*
		* @param string $var
		*
		* @return bool
		*/
		function validate_title($var)
		{
			if (empty($var)) {
				return false;
			}

			if (strlen($var) > 200) {
				return false;
			}

			return true;
		}

		/**
		* validate_lastupdated
		*
		* Ensure that lastupdated is in the standard date format
		*
		* @param string $var
		*
		* @return bool
		*/
		function validate_lastupdated($var)
		{
			return $this->is_standard_date($var);
		}

		/**
		* validate_views
		*
		* Ensure the views are a positive int
		*
		* @param string $var
		*
		* @return bool
		*/
		function validate_views($var)
		{
			return $this->is_positive_int($var);
		}

		/**
		* validate_visible
		*
		* Ensure visible is a 0 or a 1
		*
		* @param string $var
		*
		* @return bool
		*/
		function validate_visible($var)
		{
			return ($var == 0 || $var == 1);
		}

		/**
		* validate_featured
		*
		* Ensure featured is a 0 or a 1
		*
		* @param string $var
		*
		* @return bool
		*/
		function validate_featured($var)
		{
			return ($var == 0 || $var == 1);
		}

		/**
		* validate_workflowstatus
		*
		* Ensure the workflowstatus is valid
		*
		* @param string $var
		*
		* @return bool
		*/
		function validate_workflowstatus($var)
		{
			$valid_workflowstatus = array (
				WF_STATUS_APPROVED,
				WF_STATUS_AUTO_APPROVED,
				WF_STATUS_DISAPPROVED,
				WF_STATUS_PENDING,
				WF_STATUS_REPENDING
			);

			return in_array($var, $valid_workflowstatus);
		}
		
		/**
		* validate_sortorder
		*
		* Ensure the sortorder is an int
		*
		* @param string $var
		*
		* @return bool
		*/
		function validate_sortorder($var)
		{
			return $this->is_int($var);
		}

		/**
		* validate_posvotes
		*
		* Ensure the positive votes are pos int
		*
		* @param string $var
		*
		* @return bool
		*/
		function validate_posvotes($var)
		{
			return $this->is_positive_int($var);
		}

		/**
		* validate_negvotes
		*
		* Ensure the negative votes are a pos int
		*
		* @param string $var
		*
		* @return bool
		*/
		function validate_negvotes($var)
		{
			return $this->is_positive_int($var);
		}

		/**
		* validate_score
		*
		* Ensure the score is an int
		*
		* @param string $var
		*
		* @return bool
		*/
		function validate_score($var)
		{
			return $this->is_int($var);
		}

		/**
		* validate_emailed
		*
		* Ensure that emailed is a pos int
		*
		* @param string $var
		*
		* @return bool
		*/
		function validate_emailed($var)
		{
			return $this->is_positive_int($var);
		}

		/**
		* validate_detectrelated
		*
		* Ensure that detectrelated is a 0 or a 1
		*
		* @param string $var
		*
		* @return bool
		*/
		function validate_detectrelated($var)
		{
			return ($var == 0 || $var == 1);
		}

		/**
		* validate_related
		*
		* Ensure the related string isn't too long
		*
		* @param string $var
		*
		* @return bool
		*/
		function validate_related($var)
		{
			if (strlen($var) > 100) {
				return false;
			}

			return true;
		}

		/**
		* validate_metakeywords
		*
		* Ensure the meta keywords are not too long
		*
		* @param string $var
		*
		* @return bool
		*/
		function validate_metakeywords($var)
		{
			if (strlen($var) > 255) {
				return false;
			}

			return true;
		}

	}

?>
